package com.sxj.corejava.code12_jdbc;

import com.sxj.corejava.util.DataAccessException;
import com.sxj.corejava.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 石小俊
 * @date 2024年07月03日 10:26
 */
public class Test11_批处理 {

    public static void main(String[] args) {
        test02();
        test01();
    }

    public static void test01() {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            long begin = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                ps.setString(1, "test");
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                ps.executeUpdate();
            }
            long end = System.currentTimeMillis();
            System.out.println("普通操作添加1000条数据共耗费了" + (end - begin) + "毫秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void test02() {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            long begin = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                ps.setString(1, "test");
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                // 使用批处理
                // 将ps对象添加到缓冲区
                ps.addBatch();
            }

            // 全部数据添加到缓冲区之后,批量执行
            ps.executeBatch();
            long end = System.currentTimeMillis();
            System.out.println("批处理操作添加1000条数据共耗费了" + (end - begin) + "毫秒");
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }


}
